package com.example.compose


import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.RequiresApi
import androidx.compose.animation.*
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Menu
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.*
import androidx.compose.ui.graphics.Color.Companion.Transparent
import androidx.compose.ui.graphics.drawscope.Fill
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.input.pointer.*
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.unit.toSize
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.graphics.drawable.updateBounds
import androidx.core.view.WindowCompat
import androidx.lifecycle.Lifecycle
import com.example.compose.socket.Server
import com.example.compose.ui.theme.ComposeTheme
import com.example.compose.ui.theme.StatusBarColor
import com.example.compose.ui.theme.TextBack
import com.example.compose.ui.theme.TextHint
import com.example.compose.ui.wifi.WIFIManager
import com.example.compose.utils.DataStoreManager
import com.xiaotie.colorPicker.RoundColorPaletteHSV360
import kotlinx.coroutines.launch
import kotlin.math.roundToInt


class MainActivity : ComponentActivity() {

    private val hsvchahe = floatArrayOf(0f, 1f, 1f)

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //设置沉浸式
        WindowCompat.setDecorFitsSystemWindows(window, false)
        window.statusBarColor = StatusBarColor
        var wifiManager = WIFIManager(context = baseContext)
        try {
            error("抛出异常")
        }catch (e:Exception){

        }
//        var scanResults = wifiManager.scanResults()
//        var connectionInfo = wifiManager.connectionInfo().toString()
        setContent{
            var connectionInfo by remember { mutableStateOf("null") }
            SideEffect {
                connectionInfo = wifiManager.connectionInfo().toString()
            }
            LazyColumn(modifier = Modifier
                .fillMaxSize()
                .padding(60.dp, 60.dp)) {
                item {
                    Button(onClick = {
                        connectionInfo = wifiManager.connectionInfo().toString()
                    }) {
                        Text(text = connectionInfo)
                    }
                    Spacer(modifier = Modifier.height(100.dp))
                    Button(onClick = {
                        var intentService:Intent = Intent(baseContext, ForeService::class.java)
                        bindService(intentService, object : ServiceConnection {
                            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {

                            }

                            override fun onServiceDisconnected(name: ComponentName?) {

                            }
                        }, Context.BIND_AUTO_CREATE);
                        startForegroundService(intentService)
                    }) {
                        Text(text = connectionInfo)
                    }
                }
            }
        }
//        mapOf(arrayOf(0,7,13) to android.graphics.Color.parseColor("0x9903A9F4"))

//        setContent {
//            DefaultPreview()
//            BN()
//            Column(modifier = Modifier.fillMaxSize().wrapContentSize()) {
//
//                // Create a linear gradient that shows red in the top left corner
//                // and blue in the bottom right corner
//                val linear = Brush.linearGradient(listOf(Color.Red, Color.Blue))
//
//                Box(modifier = Modifier.size(120.dp).background(linear))
//
//                Spacer(modifier = Modifier.size(20.dp))
//
//                // Create a radial gradient centered about the drawing area that is green on
//                // the outer
//                // edge of the circle and magenta towards the center of the circle
//                val radial = Brush.radialGradient(listOf(Color.Green, Color.Magenta))
//                Box(modifier = Modifier.size(120.dp).background(radial))
//
//                Spacer(modifier = Modifier.size(20.dp))
//
//                // Create a radial gradient centered about the drawing area that is green on
//                // the outer
//                // edge of the circle and magenta towards the center of the circle
//                val sweep = Brush.sweepGradient(listOf(Color.Cyan, Color.Magenta))
//                Box(modifier = Modifier.size(120.dp).background(sweep))
//            }
//            Column(modifier= Modifier
//                .background(Color.Black)
//                .fillMaxHeight()
//                .fillMaxWidth()) {
//                Spacer(modifier = Modifier.height(50.dp))
////                colorPicker(20f,5f)
//                Image(painter = rememberImagePainter(
//                    data = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F201207%2F14%2F20120714145115_5GLF5.thumb.400_0.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1651977296&t=0799c73469915b079dd9c65824f90033",
//                    builder = {
//                        //可以单独设置4个角的圆角度
//                        transformations(RoundedCornersTransformation(50f,50f,30f,30f))
//                    }),
//                    contentDescription = null)
//            }
//            Greeting("99")
//            AnimateMainContent(mainContentVisible = MutableTransitionState(false))
//        }
    }

    override fun onDestroy() {
        super.onDestroy()
//        unbindService(intentService)
    }




}




@OptIn(ExperimentalAnimationApi::class)
@Composable
fun AnimatedVisibilityScope.Item(
    modifier: Modifier,
    backgroundColor: Color
) {
    // Creates a custom enter/exit animation for scale property.
    val scale by transition.animateFloat(label = "") { enterExitState ->
        // Enter transition will be animating the scale from 0.9f to 1.0f
        // (i.e. PreEnter -> Visible). Exit transition will be from 1.0f to
        // 0.5f (i.e. Visible -> PostExit)
        when (enterExitState) {
            EnterExitState.PreEnter -> 0.9f
            EnterExitState.Visible -> 1.0f
            EnterExitState.PostExit -> 0.5f
        }
    }

    // Since we defined `Item` as an extension function on AnimatedVisibilityScope, we can use
    // the `animateEnterExit` modifier to produce an enter/exit animation for it. This will
    // run simultaneously with the `AnimatedVisibility`'s enter/exit.
    Box(

        modifier
            .fillMaxWidth()
            .padding(5.dp)
            .animateEnterExit(
                // Slide in from below,
                enter = slideInVertically(initialOffsetY = { it }),
                // No slide on the way out. So the exit animation will be scale (from the custom
                // scale animation defined above) and fade (from AnimatedVisibility)
                exit = ExitTransition.None
            )
            .graphicsLayer {
                scaleX = scale
                scaleY = scale
            }
            .clip(RoundedCornerShape(20.dp))
            .background(backgroundColor)
            .fillMaxSize()
    ) {
        // Content of the item goes here...
    }
}

@OptIn(ExperimentalAnimationApi::class)
@Composable
fun AnimateMainContent(mainContentVisible: MutableTransitionState<Boolean>) {
    Box {
        // Use the `MutableTransitionState<Boolean>` to specify whether AnimatedVisibility
        // should be visible. This will also allow AnimatedVisibility animation states to be
        // observed externally.
        AnimatedVisibility(
            visibleState = mainContentVisible,
            modifier = Modifier.fillMaxSize(),
            enter = fadeIn(),
            exit = fadeOut()
        ) {
            Box {
                Column(Modifier.fillMaxSize()) {
                    // We have created `Item`s below as extension functions on
                    // AnimatedVisibilityScope in this example. So they can define their own
                    // enter/exit to run alongside the enter/exit defined in AnimatedVisibility.
                    Item(Modifier.weight(1f), backgroundColor = Color(0xffff6f69))
                    Item(Modifier.weight(1f), backgroundColor = Color(0xffffcc5c))
                }
                // This FAB will be simply fading in/out as specified by the AnimatedVisibility
                FloatingActionButton(
                    onClick = {},
                    modifier = Modifier
                        .align(Alignment.BottomEnd)
                        .padding(20.dp),
                    backgroundColor = MaterialTheme.colors.primary
                ) { Icon(Icons.Default.Favorite, contentDescription = null) }
            }
        }

        // Here we can get a signal for when the Enter/Exit animation of the content above
        // has finished by inspecting the MutableTransitionState passed to the
        // AnimatedVisibility. This allows sequential animation after the enter/exit.
        AnimatedVisibility(
            // Once the main content is visible (i.e. targetState == true), and no pending
            // animations. We will start another enter animation sequentially.
            visible = mainContentVisible.targetState && mainContentVisible.isIdle,
            modifier = Modifier.align(Alignment.Center),
            enter = expandVertically(),
            exit = fadeOut(animationSpec = tween(50))
        ) {
            Text("Transition Finished")
        }
    }
}

@Composable
fun Greeting1(name: String) {
    val offsetX = remember { mutableStateOf(0f) }
    val offsetY = remember { mutableStateOf(0f) }
    var size by remember { mutableStateOf(androidx.compose.ui.geometry.Size.Zero) }
    Box(
        Modifier
            .fillMaxSize()
            .onSizeChanged { size = it.toSize() }
    ) {
        Box(
            Modifier
                .offset { IntOffset(offsetX.value.roundToInt(), offsetY.value.roundToInt()) }
                .size(50.dp)
                .background(Color.Blue)
                .pointerInput(Unit) {
                    detectDragGesturesAfterLongPress { _, dragAmount ->
                        val original = Offset(offsetX.value, offsetY.value)
                        val summed = original + dragAmount
                        val newValue = Offset(
                            x = summed.x.coerceIn(0f, size.width - 50.dp.toPx()),
                            y = summed.y.coerceIn(0f, size.height - 50.dp.toPx())
                        )
                        offsetX.value = newValue.x
                        offsetY.value = newValue.y
                    }
                }
        )
    }
}


@ExperimentalMaterialApi
@Composable
fun DefaultPreview1(){
    val scope = rememberCoroutineScope()
    val selection = remember { mutableStateOf(1) }
    val scaffoldState = rememberBackdropScaffoldState(BackdropValue.Concealed)
    LaunchedEffect(scaffoldState) {
        scaffoldState.reveal()
    }
    BackdropScaffold(
        scaffoldState = scaffoldState,
        appBar = {
            TopAppBar(
                title = { Text("Backdrop scaffold") },
                modifier = Modifier.padding(0.dp,50.dp,0.dp,0.dp),
                navigationIcon = {
                    if (scaffoldState.isConcealed) {
                        IconButton(onClick = { scope.launch { scaffoldState.reveal() } }) {
                            Icon(Icons.Default.Menu, contentDescription = "Localized description")
                        }
                    } else {
                        IconButton(onClick = { scope.launch { scaffoldState.conceal() } }) {
                            Icon(Icons.Default.Close, contentDescription = "Localized description")
                        }
                    }
                },
                actions = {
                    var clickCount by remember { mutableStateOf(0) }
                    IconButton(
                        onClick = {
                            // show snackbar as a suspend function
                            scope.launch {
                                scaffoldState.snackbarHostState.showSnackbar("Snackbar #${++clickCount}")
                            }
                        }
                    ) {
                        Icon(Icons.Default.Favorite, contentDescription = "Localized description")
                    }
                },
                elevation = 0.dp,
                backgroundColor = Color.Transparent
            )
        },
        backLayerContent = {
            LazyColumn {
                items(if (selection.value >= 3) 3 else 5) {
                    ListItem(
                        Modifier.clickable {
                            selection.value = it
                            scope.launch { scaffoldState.conceal() }
                        },
                        text = { Text("Select $it") }
                    )
                }
            }
        },
        frontLayerContent = {
            Text("Selection: ${selection.value}")
            LazyColumn {
                items(50) {
                    ListItem(
                        text = { Text("Item $it") },
                        icon = {
                            Icon(
                                Icons.Default.Favorite,
                                contentDescription = "Localized description"
                            )
                        }
                    )
                }
            }
        }
    )
}

@OptIn(ExperimentalGraphicsApi::class)
@Composable
fun colorPicker(radius:Float,stroke:Float) {
    val colorCount = 360
    val colorAngleStep = 360 / colorCount
    val colors = mutableListOf<Color>()
    //存储选中颜色
    val hsv = floatArrayOf(0f, 1f, 1f)
    for (i in 0..colorCount) {
        hsv[0] = (i * colorAngleStep % 360).toFloat()
        colors.add(Color.hsv(hsv[0],hsv[1],hsv[2]))
    }
    val x = rememberSaveable{ mutableStateOf(-1f) }
    val y = rememberSaveable{ mutableStateOf(-1f) }
    Canvas(modifier = Modifier
        .fillMaxWidth()
        .height(200.dp)
        .padding(5.dp)
        .pointerInput(Unit) {
            forEachGesture {
                awaitPointerEventScope {
                    val event = awaitPointerEvent(PointerEventPass.Initial)
                    if (event.changes
                            .firstOrNull()
                            ?.changedToDown() == true
                    ) {
                        var newValue = Offset(
                            x = event.changes.first().position.x.coerceIn(
                                radius.dp.toPx() + stroke,
                                size.width - radius.dp.toPx() - stroke
                            ),
                            y = event.changes.first().position.y.coerceIn(
                                radius.dp.toPx() + stroke,
                                size.height - radius.dp.toPx() - stroke
                            )
                        )
                        x.value = newValue.x
                        y.value = newValue.y
                        hsv[0] =
                            (newValue.x - (radius.dp.toPx() + stroke)) / (size.width - 2 * radius.dp.toPx()) * 360
                        hsv[1] =
                            (newValue.y - (radius.dp.toPx() + stroke)) / (size.height - 2 * radius.dp.toPx())
                        Log.d("TAG", "newValue111-->$newValue")
                        val down = awaitFirstDown(requireUnconsumed = true)
                        var drag: PointerInputChange?
                        do {
                            drag = awaitTouchSlopOrCancellation(down.id) { change, _ ->
                                change.consumePositionChange()
                            }
                        } while (drag != null && !drag.positionChangeConsumed())
                        if (drag != null) {
                            !drag(drag.id) {
                                newValue = Offset(
                                    x = it.position.x.coerceIn(
                                        radius.dp.toPx() + stroke,
                                        size.width - radius.dp.toPx() - stroke
                                    ),
                                    y = it.position.y.coerceIn(
                                        radius.dp.toPx() + stroke,
                                        size.height - radius.dp.toPx() - stroke
                                    )
                                )
                                x.value = newValue.x
                                y.value = newValue.y
                                hsv[0] =
                                    (newValue.x - (radius.dp.toPx() + stroke)) / (size.width - 2 * radius.dp.toPx()) * 360
                                hsv[1] =
                                    (newValue.y - (radius.dp.toPx() + stroke)) / (size.height - 2 * radius.dp.toPx())
                                Log.d("TAG", "newValue333-->$newValue")
                                it.consumePositionChange()
                            }
                        }
                    }
                }
            }
        }
    ) {
        //初始化
        if(x.value == -1f){
            x.value = radius.dp.toPx()+stroke
            y.value = radius.dp.toPx()+stroke
            hsv[0] = 0f;
            hsv[1] = 0f;
            hsv[2] = 1f;
        }
        //hsv h 的渐变色
        drawRoundRect(
            brush = Brush.horizontalGradient(colors = colors, startX = radius.dp.toPx(), endX = size.width -radius.dp.toPx()),
            cornerRadius = CornerRadius(radius.dp.toPx(), radius.dp.toPx()),
            style = Fill,
            size = Size(size.width , size.height)
        )
        //白色到透明的渐变色
        drawRoundRect(
            brush = Brush.verticalGradient(colors = listOf(Color.White, Color.Transparent), startY = radius.dp.toPx(), endY = size.height-radius.dp.toPx()),
            cornerRadius = CornerRadius(radius.dp.toPx(), radius.dp.toPx()),
            style = Fill,
            size = Size(size.width , size.height)
        )
        //白色边框
        drawRoundRect(
            color= Color.White,
            cornerRadius = CornerRadius(radius.dp.toPx(), radius.dp.toPx()),
            style = Stroke(width = stroke),
            topLeft = Offset(stroke/2f, stroke/2f),
            size = Size(size.width-stroke, size.height-stroke)
        )
        //黑色边框
        drawRoundRect(
            color= Color.Black,
            cornerRadius = CornerRadius(radius.dp.toPx(), radius.dp.toPx()),
            style = Stroke(width = stroke/5f),
            topLeft = Offset(stroke, stroke),
            size = Size(size.width-2*stroke, size.height-2*stroke)
        )
        //圆
        drawCircle(
            color = Color.hsv(hsv[0],hsv[1],hsv[2]),
            radius = radius.dp.toPx(),
            style = Fill,
            center = Offset(x.value,y.value)
        )
        //圆黑色边框
        drawCircle(
            color = Color.Gray,
            radius = radius.dp.toPx()-stroke,
            style = Stroke(width = stroke),
            center = Offset(x.value,y.value)
        )
        //白色黑色边框
        drawCircle(
            color = Color.White,
            radius = radius.dp.toPx()-stroke/2,
            style = Stroke(width = stroke),
            center = Offset(x.value,y.value)
        )
    }
}


@SuppressLint("CoroutineCreationDuringComposition")
@Composable
fun DefaultPreview11(onClick: () -> Unit) {
    val scope = rememberCoroutineScope()
    val bgImg = LocalContext.current.getDrawable(R.mipmap.home_bg_2)
    var text by rememberSaveable { mutableStateOf("Hello") }
    scope.launch {
        DataStoreManager.name.collect { value ->
            text = value
        }
    }
    Lifecycle.State.STARTED
    var text1 by rememberSaveable { mutableStateOf("Hello") }
    var execCommand: ShellUtils.CommandResult? = null
//        val fileName = "crash.txt"
//        val path: String =
//            filesDir.absolutePath + File.separator.toString() + "hfile"
//        if (!File(path).exists()) {
//            try {
//                File(path).mkdir()
//            } catch (e: java.lang.Exception) {
//            }
//        }
//        val strCmd = "logcat *:V | grep  \"com.example.compose\" >$path/$fileName"
//        Thread {
//            try {
//
//                execCommand = ShellUtils.execCommand(strCmd, false)
//                Log.e("TAG","1234")
//
//            } catch (e: Exception) {
//                e.printStackTrace()
//            }
//        }.start()
//        var bgImg: ImageBitmap? = null
//        runBlocking {
//            launch{
//                Thread {
//                    try {
//                        bgImg = Picasso.get().load(R.mipmap.bg).get().asImageBitmap()
//                    } catch (e: IOException) {
//                        e.printStackTrace()
//                    }
//                }.start()
//
//            }
//        }
    ComposeTheme {
        Surface {
            Column(
                modifier = Modifier
                    .fillMaxHeight()
                    .drawBehind {
                        bgImg?.updateBounds(0, 0, size.width.toInt(), size.height.toInt())
                        bgImg?.draw(drawContext.canvas.nativeCanvas)
                    }
//                   .background(
//                       Brush.horizontalGradient(
//                           listOf(Color.Red, Color.Green, Color.Blue),
//                           startX = 10.0f,
//                           endX = 20.0f
//                       )
//                   )
//                    .paint(
//                        painter = painterResource(id = R.mipmap.bg),
//                        contentScale = ContentScale.FillBounds
//                    )
            ) {
                Spacer(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(50.dp),
                )
//                    Greeting("Android")
                AnnotatedClickableText()
                TextField(
                    value = text,
                    onValueChange = { text = it },
//                        label = { Text(text = "Label",color = TextHint) },
                    placeholder = { Text(text = "Label",color = TextHint) },
                    colors = TextFieldDefaults.textFieldColors(backgroundColor = TextBack,unfocusedIndicatorColor = Transparent)
                )
                OutlinedTextField(
                    value = text,
                    onValueChange = { text = it },
                    label = { Text("path") }
                )
//                    Box() {
                BasicTextField(
                    value = text,
                    onValueChange = { text = it },
                    textStyle = TextStyle(color = Color.Unspecified),
                    modifier = Modifier
                        .fillMaxWidth()
                        .wrapContentHeight()
                        .padding(10.dp)
                )
//                        if(text.isEmpty()) Text(text = "Label",color = TextHint,modifier = Modifier.padding(12.dp,10.dp,0.dp,0.dp))
//                    }

//                    Alert()
//                    Alert1()
                BottomNavigat {
                    Thread {
                        Server().startService()
                    }.start()
                }
                BottomNavigat { onClick() }
                Button(onClick = {
                    scope.launch {
                        DataStoreManager.saveName(text)
                    }
                }) {
                    Text("text")
                }
                LazyColumn(){
                    item {
                        Card {
                            Text(text1)
                        }
                    }
                }

                val checkedState = remember { mutableStateOf(true) }
                Checkbox(
                    checked = checkedState.value,
                    onCheckedChange = { checkedState.value = it }
                )

                AndroidView(factory = {
                   val roundColorPalette = RoundColorPaletteHSV360(it)
                    roundColorPalette
                })
            }
        }
    }

}

@Composable
fun BottomNavigat(onClick:()->Unit) {
    BottomNavigation {
        BottomNavigationItem(
            icon = {
                Icon(
                    Icons.Filled.Favorite,
                    contentDescription = "Favorite"
                )
            },
            modifier=Modifier.padding(),
            selected = false,
            onClick = onClick
        )
    }
}

@Composable
fun BN(){
    var selectedItem by remember { mutableStateOf(0) }
    val items = listOf("Songs", "Artists", "Playlists")

    BottomNavigation {
        items.forEachIndexed { index, item ->
            BottomNavigationItem(
                icon = { Icon(Icons.Filled.Favorite, contentDescription = null) },
                label = { Text(item) },
                selected = selectedItem == index,
                onClick = { selectedItem = index }
            )
        }
    }
}

@Composable
fun Alert1(){
    val openDialog = remember { mutableStateOf(true) }
    if (openDialog.value) {
        AlertDialog(
            onDismissRequest = {
                openDialog.value = false
            },
            title = {
                Text(text = "Title")
            },
            text = {
                Text(
                    "This area typically contains the supportive text " +
                            "which presents the details regarding the Dialog's purpose."
                )
            },
            buttons = {
                Row(
                    modifier = Modifier.padding(all = 8.dp),
                    horizontalArrangement = Arrangement.Center
                ) {
                    Button(
                        modifier = Modifier.fillMaxWidth(),
                        onClick = { openDialog.value = false }
                    ) {
                        Text("Dismiss")
                    }
                }
            }
        )
    }
}


@Composable
fun Alert() {
    val openDialog = remember { mutableStateOf(true) }
    if(openDialog.value){
        AlertDialog(
            onDismissRequest = {
                openDialog.value = false
            },
            title = { Text(text = "Title") },
            text = {
                Text(
                    "This area typically contains the supportive text " +
                            "which presents the details regarding the Dialog's purpose."
                )
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        openDialog.value = false
                    }
                ) {
                    Text("Confirm")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = {
                        openDialog.value = false
                    }
                ) {
                    Text("Dismiss")
                }
            }
        )
    }
}

@SuppressLint("QueryPermissionsNeeded")
@Composable
fun AnnotatedClickableText() {
    val annotatedText = buildAnnotatedString {
        append("Click ")

        // We attach this *URL* annotation to the following content
        // until `pop()` is called
        pushStringAnnotation(tag = "URL",
            annotation = "http://fcdm1.com/acg/")
        withStyle(style = SpanStyle(color = Color.Blue,
            fontWeight = FontWeight.Bold)
        ) {
            append("here")
        }
        append("Click ")
        pop()
    }

    ClickableText(
        text = annotatedText,
        onClick = { offset ->
            // We check if there is an *URL* annotation attached to the text
            // at the clicked position
            annotatedText.getStringAnnotations(
                tag = "URL",
                start = offset,
                end = offset)
                .firstOrNull()?.let { annotation ->
                    // If yes, we log its value
                    val context = App().getContext()
                    val intent = Intent()
                    intent.action = Intent.ACTION_VIEW
                    intent.addCategory(Intent.CATEGORY_BROWSABLE)
                    intent.data = Uri.parse(annotation.item)
                    if (intent.resolveActivity(context.packageManager) != null) {
                        context.startActivity(Intent.createChooser(intent, "请选择浏览器"))
                    } else {
                        Toast.makeText(context, "请下载浏览器", Toast.LENGTH_SHORT).show()
                    }
//                        var intent = Intent(this@MainActivity, MainActivity3::class.java)
//                        intent.putExtra("url","")
//                        startActivity(intent)
//                        finish()

                }
        },
        style = TextStyle(fontSize = 30.sp)
    )
}

